#!usr/bin/env python
# -*- coding:utf-8 _*-
""" 
@author:robot
@file: tap_connector10_elasticsearch.py
@version:
@time: 2022/01/13 
"""
from elasticsearch import Elasticsearch
from elasticsearch.exceptions import *
from TapClientConnector.connector.tap_connector00_base import *


class TAPESConnector(TAPConnectorBase):

    def __init__(self, kwargs):
        super().__init__(kwargs)
        host = self.FORMAT_DB_INFO.get('host')
        port = self.FORMAT_DB_INFO.get('port')
        user = self.FORMAT_DB_INFO.get('user')
        password = self.FORMAT_DB_INFO.get('password')
        self.connector = Elasticsearch(
            f'{host}:{port}',
        )
        if user:
            self.connector = Elasticsearch(
                f'{user}:{password}@{host}:{port}',
            )

    @connector_exec_logger
    def _exec(self, data):
        operate = data.get('operate')
        index = data.get('index')
        try:
            if operate == 'drop':
                exec_result = self.connector.indices.delete(index=index)
                if exec_result.get('acknowledged'):
                    return 'delete index success'
            else:
                raise NotSupport
        except NotFoundError:
            logger.warning('ES NOT FOUND INDEX')

    def _query(self, index):
        """
        es 作为目标，同步的表都会变成小写
        :param index:
        :return:
        """
        try:
            es_raw_data = self.connector.search(index=index.lower())
            return [data.get('_source') for data in es_raw_data.get('hits').get('hits')]
        except NotFoundError:
            logger.warning('NO SUCH INDEX')
            return []

    # COMMON FUNC
    @connector_query_logger
    def show_tables(self):
        result = [name for name, _ in self.connector.indices.get_alias().items()]
        return result

    # **DDL**

    @generate_logger
    def generate_drop(self, table=None):
        """
        :param index:
        :return:
        """
        if table:
            self.CURRENT_TABLE = table
        return {
            'operate': 'drop',
            'index': self.CURRENT_TABLE.lower(),
        }

    # ** DML **
    @generate_logger
    def generate_select(self, table=None, order=''):
        if table:
            self.CURRENT_TABLE = table
        """
        :param index:
        :return:
        """
        return self.CURRENT_TABLE.lower()
